package 二叉树;

import java.util.Deque;
import java.util.LinkedList;

public class 二叉树的最大深度 {
    public class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    /*
      递归法 比较左右子树的深度 然后再加一（加一是加上当前的根节点）
     */
    public int maxdepth(TreeNode root){
        if (root == null) return 0;
        int leftdepth = maxdepth(root.left);
        int rightdepth = maxdepth(root.right);
        return Math.max(leftdepth,rightdepth)+1;
    }

    /*
    迭代法，使用层序遍历
     */
    public int maxdepth2(TreeNode root){
         if (root == null) return 0;
        Deque<TreeNode> list = new LinkedList<>();
        list.offer(root);
        int depth = 0;
        while (!list.isEmpty()){
            int size = list.size();
            depth++;
            for (int i = 0; i < size; i++) {
                TreeNode poll = list.poll();
                if (poll.left!=null) list.offer(poll.left);
                if (poll.right!=null) list.offer(poll.right);
            }
        }
            return depth;
    }

}
